package com.example.demo.listener;

import com.example.demo.db.MockDB;
import com.example.demo.pojo.ClientInfoVo;
import com.example.demo.util.HttpUtil;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;
//session监听器，当session被操作时触发
@WebListener
public class SessionListener implements HttpSessionListener {
  //创建事件
  @Override
  public void sessionCreated(HttpSessionEvent se) {

  }

  //销毁事件
  @Override
  public void sessionDestroyed(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    String token = (String) session.getAttribute("token");
    //销毁用户信息
    MockDB.T_TOKEN.remove(token);
    List<ClientInfoVo> clientInfoVoList = MockDB.T_CLIENT_INFO.remove(token);
    if(clientInfoVoList.size()!=0){
      for (ClientInfoVo vo : clientInfoVoList) {
        try {
          //遍历通知客户端注销
          HttpUtil.sendRequest(vo.getClientUrl(), vo.getJsessionId());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
}
